from django.core.paginator import Paginator

from tppt.lib.actions import *
from tppt.lib import utils

class IndexAction(TemplateAction):
	template='lib/base_index.html'

	def get_param_defaults(self):
		defaults={
				'page': 1,
				'page_size': 20,
				}
		return defaults

	def get_pagination(self, page):
		paginator=page.paginator
		if paginator.num_pages<=1:
			return None
		res=[]
		
		page_range=utils.union_ranges(range(1,3), range(page.number-4, page.number+4),	 
									range(paginator.num_pages-3, paginator.num_pages))
		page_range=utils.filter(lambda x:x<=paginator.num_pages, page_range) 
		
		prev=None
		for i in page_range:
			if prev and i!=prev+1:
				res.append(('...', None))
			if i==page.number:
				res.append((i, None))
			else:
				url=self.get_url({'page':i})
				res.append( (i, url) )
			prev=i
		return res

	def perform_template(self):
		query_set=self.object
		model=query_set.model
		paginator=Paginator(query_set, self.params['page_size'])
		page=paginator.page(self.params['page'])
		pagination=self.get_pagination(page)
		
		cols=model.get_list_fields();
		
		query_set_actions=get_actions_details(query_set)
		query_set_actions=utils.filter(lambda x: x['name']!='index', query_set_actions)
			
		params={
			'model':model,
			'query_set_actions': query_set_actions, 
			'cols':cols, 
			'page': page,
			'pagination': pagination,
			}
		return params

def GetInAction(object=None, request=None, **kwargs):
	from django.db.models.loading import get_model
	
	model=object.__class__
	inner_objects=model._meta.actions.inner_objects
	if not inner_objects:
		raise tppt.lib.Error()
	target_model_name, target_prop_name=inner_objects
	
	target_model=get_model('data', target_model_name)
	
	entity_set=target_model.objects.all().filter_ref(target_prop_name, object)
	res=IndexAction(entity_set, request=request, **kwargs)
	res.image_url='/static/images/icon_folder.gif'
	res.get_caption=lambda: 'Get in'
	return res
		
class DeleteAllAction(GetPostAction):
	template='lib/base_question.html'
	def get_template_params(self):
		model=self.object.model
		return {
			'question': 'Do you really want to delete all records in table %s?' % model.__name__,
			'options': [('yes', 'Yes'), ('no', 'No')]
			}
	def success(self):
		entity_set=self.object
		if self.request.POST.has_key('yes'):
			for obj in entity_set.all():
				obj.delete()

class DeleteAction(GetPostAction):
	image_url='/static/images/icon_delete.gif'
	template='lib/base_question.html'
	def get_template_params(self):
		entity=self.object
		model=entity.__class__
		params={'options': [('yes', 'Yes'), ('no', 'No')]}
		params['question']='Do you really want to delete entity %s?' % str(entity)
		return params
	def success(self):
		entity=self.object
		if self.request.POST.has_key('yes'):
			entity.delete()

		
